package com.wxy.bytebuffer;

import java.nio.ByteBuffer;

/**
 * @author 47868
 */
public class 黏包和半包 {
    public static void split(ByteBuffer buffer){
        for (int i = 0; i < buffer.limit(); i++) {
            if (buffer.get(i) == '\n') {
                int data = i+1-buffer.position();
                ByteBuffer buffer1 = ByteBuffer.allocate(data);
                for (int j = 0;j < data;j++){
                    buffer1.put(buffer.get());
                }
                buffer1.flip();
                while(buffer1.hasRemaining()){
                    System.out.print((char) buffer1.get());
                }
                System.out.println(buffer.position());
            }
        }
        // 处理剩余的半包数据
        if (buffer.position() < buffer.limit()) {
            while (buffer.hasRemaining()) {
                System.out.print((char) buffer.get());
            }
        } else {
            // 如果缓冲区已空，直接清空
            buffer.clear();
        }
    }
    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(50);
        buffer.put("hello world\nlet is go\nho".getBytes());
        buffer.put("w are you".getBytes());
        buffer.flip();
        split(buffer);
    }
}
